package com.mc.read.adminapi.manager;

import com.mc.read.common.MapConfig;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.dao.mapper.sys.SyspermissionMapper;
import com.mc.read.dao.mapper.sys.SysuserMapper;
import com.mc.read.dao.models.sys.Sysuser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @author liuhao
 * @date 2019/6/12 14:53
 */
@Service
public class CacheManager {
    @Autowired
    SysuserMapper sysuserMapper;
    @Autowired
    SyspermissionMapper syspermissionMapper;

    public Sysuser getSysUser(Integer userid) {
        if (ObjectUtils.isEmpty(userid)) {
            throw new ServiceException(203020, "用户不存在");
        }
        Sysuser sysuser = (Sysuser) MapConfig.userMap.get(userid);
        if (ObjectUtils.isEmpty(sysuser)) {
            sysuser = sysuserMapper.selectByPrimaryKey(userid);
            if (ObjectUtils.isEmpty(sysuser)) {
                throw new ServiceException(203020, "用户不存在");
            }
            MapConfig.userMap.put(userid, sysuser);
        }
        return sysuser;
    }

    public Set<String> getUserPer(Integer userid) {
        if (ObjectUtils.isEmpty(userid)) {
            throw new ServiceException(203020, "用户不存在");
        }
        Set<String> set = (Set<String>) MapConfig.userPerMap.get(userid);
        if (ObjectUtils.isEmpty(set)) {
            set = syspermissionMapper.selectUserPer(userid);
            if (ObjectUtils.isEmpty(set) || set.size() == 0) {
                throw new ServiceException(203020, "权限不足");
            }
            MapConfig.userPerMap.put(userid, set);
        }
        return set;
    }

    public void setUserInfo(Integer userid) {
        Sysuser sysuser = sysuserMapper.selectByPrimaryKey(userid);
        if (ObjectUtils.isEmpty(sysuser)) {
            throw new ServiceException(203020, "用户不存在");
        }
        MapConfig.userMap.put(userid, sysuser);
    }

    public void setUserPer(Integer userid) {
        Set<String> set = syspermissionMapper.selectUserPer(userid);
        if (ObjectUtils.isEmpty(set) || set.size() == 0) {
            MapConfig.userPerMap.put(userid, null);
        }
        MapConfig.userPerMap.put(userid, set);
    }




    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("xxx");
        set.add("1q23");
        MapConfig.userPerMap.put(1, set);
        set = (Set<String>) MapConfig.userPerMap.get(1);
        System.out.println(set.size());
        set = (Set<String>) MapConfig.userPerMap.get(2);
        if (ObjectUtils.isEmpty(set)) {
            System.out.println("xxxxxxxxxxxxx");
        }

    }
}
